package com.zhentao.config;

import jakarta.servlet.http.HttpSession;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;

/**
 * WebSocket握手配置
 * 支持跨域和参数传递
 */
public class GetHttpSessionConfig extends ServerEndpointConfig.Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig serverEndpointConfig, HandshakeRequest request, HandshakeResponse response) {
        try {
            // 设置跨域头（安全地处理）
            if (response.getHeaders() != null) {
                response.getHeaders().put("Access-Control-Allow-Origin", java.util.Arrays.asList("*"));
                response.getHeaders().put("Access-Control-Allow-Methods", java.util.Arrays.asList("GET, POST, OPTIONS"));
                response.getHeaders().put("Access-Control-Allow-Headers", java.util.Arrays.asList("Content-Type, Authorization"));
            }

            // 获取 HttpSession 对象
            HttpSession httpSession = (HttpSession) request.getHttpSession();

            // 将 httpSession 对象保存起来，存到 ServerEndpointConfig 对象中
            // 在 ChatEndpoint 类的 onOpen 方法就能通过 EndpointConfig 对象获取在这里存入的数据
            if (httpSession != null && serverEndpointConfig.getUserProperties() != null) {
                serverEndpointConfig.getUserProperties().put(HttpSession.class.getName(), httpSession);
            }

            // 保存查询参数
            String queryString = request.getQueryString();
            if (queryString != null && serverEndpointConfig.getUserProperties() != null) {
                serverEndpointConfig.getUserProperties().put("queryString", queryString);
            }

            // 保存ServletContext用于获取Spring ApplicationContext
            if (httpSession != null && httpSession.getServletContext() != null && serverEndpointConfig.getUserProperties() != null) {
                serverEndpointConfig.getUserProperties().put("servletContext", httpSession.getServletContext());
            }

            System.out.println("WebSocket握手成功: " + request.getRequestURI() + "?" + queryString);
        } catch (Exception e) {
            System.err.println("WebSocket握手处理失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean checkOrigin(String originHeaderValue) {
        // 允许所有来源（生产环境中应该限制具体域名）
        return true;
    }
}
